import { getCodeAPI } from '@/api/user'
import type { FormInstance } from 'vant'
import { computed, onUnmounted, ref } from 'vue'

export default function () {
  // 表单实例
  const formRef = ref<FormInstance>()
  // 倒计时
  const countdown = ref(60)
  // 是否开始计时
  const isCountingDown = ref(false)
  // 定时器ID
  let timeId: number
  // 验证码
  const code = ref<string>('')
  // 动态获取验证码状态
  const countdownText = computed(() => {
    if (isCountingDown.value) {
      return `${countdown.value}s 后重新获取`
    } else {
      return '获取验证码'
    }
  })
  // 获取验证码
  const codeHandle = async (phone: string) => {
    if (isCountingDown.value) return
    try {
      await formRef.value?.validate('phone')
      isCountingDown.value = true
      // 获取验证码
      timeId = setInterval(async () => {
        if (countdown.value > 0) {
          countdown.value--
        } else {
          clearInterval(timeId)
          isCountingDown.value = false
          countdown.value = 60
        }
      }, 1000)
      const response = await getCodeAPI(phone)
      code.value = response.data
    } catch (error) {
      console.log(error)
    }
  }
  onUnmounted(() => {
    window.clearInterval(timeId)
  })
  return {
    formRef,
    isCountingDown,
    countdownText,
    code,
    codeHandle,
  }
}
